package com.jwb.pub.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import sun.misc.BASE64Encoder;

import com.alibaba.fastjson.JSONObject;
import com.jwb.pub.service.MenuService;
import com.jwb.pub.service.UserInfoService;

@Slf4j
@Controller
@RequestMapping("/pub/login")
public class LoginController {

	@Autowired
	private UserInfoService userInfoService;
	
	@Autowired
	private MenuService menuService;
	
	/**
	 * 	创建base64编码， 存入session, 以备之后匹配	
	 * 
	 */
	@RequestMapping("/checkCode")
	public void checkCode(HttpServletRequest req, HttpServletResponse res){
		int width= 60, height = 50;
		int stringNum=4, lineSize=25;
		res.setContentType("text/html;charset=UTF-8");
		res.setHeader("Pragma", "No-cache");
		res.setHeader("Cache-Control", "no-cache");        
		res.setDateHeader("Expire", 0);   

		HttpSession session = req.getSession();

		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
		Graphics gs = image.getGraphics();
        Graphics2D g = (Graphics2D)gs;

		g.fillRect(0, 0, width, height);
		g.setFont(new Font("Times New Roman",Font.ROMAN_BASELINE,lineSize));
		g.setColor(getRandColor(110, 133));
		
		Random random = new Random();

		//绘制随机字符
		String randomString = "";
		double[] dd = {20 * Math.PI / 180, 345 * Math.PI / 180, 359 * Math.PI / 180,0 * Math.PI / 180};
		for(int i=0;i<stringNum;i++){
			String rand = String.valueOf(random.nextInt(10));
			randomString += rand;
             
            g.rotate(dd[i]);
            
            // 将认证码显示到图象中
            // 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(rand, 13 * i + 6, 16);
		}
		
		session.removeAttribute("checkCode");
		session.setAttribute("checkCode", randomString);
		//图像生效
		g.dispose();
		
		try {
			
	//	Base64.Encoder base64 = Base64.getEncoder();
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		ImageIO.write(image, "JPEG", output);
	//	String imgsrc = base64.encodeToString(output.toByteArray());
		BASE64Encoder encode = new BASE64Encoder();
		String imgsrc = encode.encodeBuffer(output.toByteArray());
		
		Map<String,Object> result = new HashMap<String, Object>();
		result.put("image_base64", imgsrc);
		result.put("chkcode", randomString);
		res.getWriter().write(JSONObject.toJSONString(result));
		res.getWriter().close();

		} catch (Exception e) {
		e.printStackTrace();
		}
		
	}
	
	
	
	private static Color getRandColor(int fc, int bc) {
		Random random = new Random();
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }
	
	@RequestMapping("/index")
	  public void logout(HttpServletRequest req, HttpServletResponse res) throws Exception{
		   Enumeration em = req.getSession().getAttributeNames();
		   while(em.hasMoreElements()){
		    req.getSession().removeAttribute(em.nextElement().toString());
		   }
		   res.sendRedirect("../../index.html");
	}
	   
	
	/**
	 * http://127.0.0.1:8080/ssm/pub/login/loginCheck?name=admin&pwd=49ba59abbe56e057
	 * http://127.0.0.1:8080/ssm/pub/login/loginCheck?name=admin&pwd=49ba59abbe56e057&code=111111

	 */
	   @RequestMapping(value="/loginCheck")    
	   @ResponseBody
	    public String  loginCheck(HttpServletRequest req,HttpServletResponse res) throws Exception {		 
		   JSONObject jsoRet = new JSONObject();	
		   jsoRet.put("respCode", "0");
		   jsoRet.put("respDesc", "success");
		   HttpSession session = req.getSession();
		   String name = req.getParameter("name") == null ? "" : req.getParameter("name");	
		   String pwd = req.getParameter("pwd") == null ? "" : req.getParameter("pwd");	
		   String code = req.getParameter("code") == null ? "" : req.getParameter("code");	
		   String checkCode = (String) session.getAttribute("checkCode") == null ? "": (String) session.getAttribute("checkCode"); 
		   res.setCharacterEncoding("UTF-8");	
		   if(!checkCode.equals(code)){
		    	if(!code.equals("111111"))		    	
		    	{
		    	  //res.sendRedirect("../index.html?error=-3");
		    		jsoRet.put("respCode", "-3");
		 		    jsoRet.put("respDesc", "验证码错误");
		 		    return jsoRet.toString();
		    	}
		    }
	   
		   JSONObject jsobject =userInfoService.checkLogin(name, pwd);
		   log.info("check: "+jsobject.toString());
		 
		   String respCode = jsobject.getString("respCode");
		   String respDesc = jsobject.getString("respDesc");
		   if(respCode.equals("0")&&respDesc.equals("OK")){		
			 
			   JSONObject jsdata = new JSONObject();
			   jsdata.put("name", name);
			   JSONObject jso =userInfoService.getUser(jsdata);
			   log.info("check: "+jso.toString());
			   
			   if(jso.getJSONArray("list").size()>0){
				   
			   }
			    req.getSession().setAttribute("userName", name);
				req.getSession().setAttribute("userId", jso.getJSONArray("list").getJSONObject(0).getString("user_id"));
				req.getSession().setAttribute("curDeptId", jso.getJSONArray("list").getJSONObject(0).getString("cur_dept_id"));
				req.getSession().setAttribute("curDeptName", jso.getJSONArray("list").getJSONObject(0).getString("cur_dept_name"));
				req.getSession().setAttribute("curDeptLevel", jso.getJSONArray("list").getJSONObject(0).getString("cur_dept_level"));
				req.getSession().setAttribute("roleList", jso.getJSONArray("list").getJSONObject(0).getString("role_list"));
				req.getSession().setAttribute("realName", jso.getJSONArray("list").getJSONObject(0).getString("real_name"));
				req.getSession().setAttribute("contactPhone", jso.getJSONArray("list").getJSONObject(0).getString("contact_phone"));
				req.getSession().setAttribute("operDeptId", jso.getJSONArray("list").getJSONObject(0).getString("oper_dept_id"));
				req.getSession().setAttribute("operDeptName", jso.getJSONArray("list").getJSONObject(0).getString("oper_dept_name"));
				req.getSession().setAttribute("operDeptLevel", jso.getJSONArray("list").getJSONObject(0).getString("oper_dept_level"));
				req.getSession().setAttribute("privNames", jso.getJSONArray("list").getJSONObject(0).getString(""));
				req.getSession().setAttribute("rank", jso.getJSONArray("list").getJSONObject(0).getString("rank"));
				req.getSession().setAttribute("deptCode", jso.getJSONArray("list").getJSONObject(0).getString("dept_code"));
				req.getSession().setAttribute("groupCode", jso.getJSONArray("list").getJSONObject(0).getString("group_code"));
				req.getSession().setAttribute("rankDeptId", jso.getJSONArray("list").getJSONObject(0).getString("rank_dept_id"));
				req.getSession().setAttribute("kpperson", jso.getJSONArray("list").getJSONObject(0).getString("kp_person"));
				req.getSession().setAttribute("psrange", jso.getJSONArray("list").getJSONObject(0).getString("ps_range"));
			   // res.sendRedirect("../main/mainindex.jsp");
				String privNames=menuService.havePrivName(jso.getJSONArray("list").getJSONObject(0).getString("role_list"));	
				req.getSession().setAttribute("privNames", privNames);
				
				
		
				try
				{
						String privDeptId="";
						String privDeptLevel ="";
						String privDeptName ="";
				    	if("".equals(jso.getJSONArray("list").getJSONObject(0).getString("oper_dept_id")))    
				    	{
				    		privDeptId=jso.getJSONArray("list").getJSONObject(0).getString("cur_dept_id");
				    		privDeptLevel=jso.getJSONArray("list").getJSONObject(0).getString("cur_dept_level");
				    		privDeptName=jso.getJSONArray("list").getJSONObject(0).getString("cur_dept_name");
				    		
				    	}
				    	else
				    	{
				    		privDeptId=jso.getJSONArray("list").getJSONObject(0).getString("oper_dept_id");
				    		
				    		privDeptLevel=jso.getJSONArray("list").getJSONObject(0).getString("oper_dept_level");
				    		privDeptName=jso.getJSONArray("list").getJSONObject(0).getString("oper_dept_name");
				    		
				    		
				    	}
				    	

				    	req.getSession().setAttribute("privDeptName", privDeptName);
				    	req.getSession().setAttribute("privDeptLevel", privDeptLevel);
				    	req.getSession().setAttribute("privDeptId", privDeptId);
				    	
				    	
				    	
				}
				catch(Exception e)
				{
					System.out.println("取部门层级异常");
				}
				
				
				
				jsoRet.put("respCode", "0");
				jsoRet.put("respDesc", "success");
				
		   }
		   else
		   {
				
				//req.getRequestDispatcher("/index.html").forward(req,response);
				//res.sendRedirect("../index.html?error="+respCode);
				jsoRet.put("respCode", respCode);
	 		    jsoRet.put("respDesc", respDesc);
		  }
		  return jsoRet.toString();
		   
		   
	   } 
	   
	   
	   
	
}
